#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
 
// 下面一个函数实现来自:https://zhidao.baidu.com/question/276891288.html
void mode_to_letter(int mode,char *str)
{
    /*-------这个函数用来把模式值转化为字符串------*/
    str[0]='-'; /*------这里的S_*****都是宏定义，用来判断模式属性-*/

    if(S_ISDIR(mode)) str[0]='d';/*-文件夹-*/
    if(S_ISCHR(mode)) str[0]='c';/*-字符设备-*/
    if(S_ISBLK(mode)) str[0]='b';/*-块设备-*/

    if(mode & S_IRUSR) str[1]='r';/*--用户的三个属性-*/
    else str[1]='-';
    if(mode & S_IWUSR) str[2]='w';
    else str[2]='-';
    if(mode & S_IXUSR) str[3]='x';
    else str[3]='-';

    if(mode & S_IRGRP) str[4]='r';/*--组的三个属性-*/
    else str[4]='-';
    if(mode & S_IWGRP) str[5]='w';
    else str[5]='-';
    if(mode & S_IXGRP) str[6]='x';
    else str[6]='-';

    if(mode & S_IROTH) str[7]='r';/*-其他人的三个属性-*/
    else str[7]='-';
    if(mode & S_IWOTH) str[8]='w';
    else str[8]='-';
    if(mode & S_IXOTH) str[9]='x';
    else str[9]='-';

    str[10]='\0';
}
int main(int argc,char *argv[])
{
    int i, ret;
    char data[20];
    struct stat buf;        
    if(argc < 2) {
        printf("stat: missing operand\n");
        printf("Try 'stat --help' for more information.\n");
        exit(-1);
    }
    // 多个文件进行循环输出
    for(i = 1;i < argc; ++i) {
        ret = stat(argv[i], &buf);
        if(-1 == ret) {
            perror("stat");
        } else {
            printf("  文件: %s\n", argv[i]);
            printf("  大小: %lld            块: %d          IO 块: %d   ", (long long) buf.st_size, (long long) buf.st_blocks, (long) buf.st_blksize);         switch (buf.st_mode & S_IFMT) {
                case S_IFBLK:  printf("block device\n");            break;
                case S_IFCHR:  printf("character device\n");        break;
                case S_IFDIR:  printf("directory\n");               break;
                case S_IFIFO:  printf("FIFO/pipe\n");               break;
                case S_IFLNK:  printf("symlink\n");                 break;
                case S_IFREG:  printf("regular file\n");            break;
                case S_IFSOCK: printf("socket\n");                  break;
                default:       printf("unknown?\n");                break;
            }
            /*--------------下面两行输出的内容还有部分没有实现---------------*/
            printf("设备: fd01h/64769d    Inode: %lld      硬链接: %lld\n", (long) buf.st_ino, (long) buf.st_nlink);          
            mode_to_letter(buf.st_mode, data);        
            printf("权限: (7204/%s)  Uid: (    %ld/    root)   Gid: (    %ld/    root)\n", data, (long) buf.st_uid, (long) buf.st_gid);
            /*---------------------------------------------------------------*/
            printf("最近访问: %s", 2017 11 ctime(&buf.st_atime));
            printf("最近更改: %s", 2017 11 ctime(&buf.st_mtime));
            printf("最近改动: %s", 2017 11 ctime(&buf.st_ctime));
            printf(" 创建时间: -\n");
        }
        
    }
    return 0;
}
